<?php

class Tools
{

  public static function getWorld()
  {
    return WorldQuery::create()->findOne();
  }

  public  static function getCurrentTurn()
  {
    return self::getWorld()->getTurn();
  }

  public static function getUser()
  {
    return sfContext::getInstance()->getUser();
  }

  /**
   * Verifies if cities has the unit type mentioned and enough troops
   *
   * @param $units array Array of units that contains city_id, type_id, total
   */
  public static function ValidateUnits($units)
  {
    foreach ($units as $unit)
    {
      $city_unit = CityUnitQuery::create()
              ->useCityQuery()
                ->filterByUserId(self::getUser()->getAttribute('user_id', null, 'sfGuardSecurityUser'))
              ->endUse()
              ->filterByUnitTypeId($unit->type_id)
              ->findOneByCityId($unit->city_id);

      if(! $city_unit || $city_unit->getUnitTypeId() != $unit->type_id || $city_unit->getTotal() < $unit->total)
        return false;
    }

    return true;
  }

  public static function getDistance($loc1, $loc2)
  {
    if (strlen($loc1) < 2)
      $loc1 = '0'.$loc1;

    if (strlen($loc2) < 2)
      $loc2 = '0'.$loc2;

    $x1 = $loc1 % 10;
    $y1 = substr($loc1, 0, 1);

    $x2 = $loc2 % 10;
    $y2 = substr($loc2, 0, 1);

    $x = ( pow($x2-$x1,2));
    $y = ( pow($y2-$y1,2));

    $distance = ( sqrt($x + $y) );

    return ceil($distance);
  }


  public static function display($var)
  {
    echo '<pre>';
    print_r($var);
    echo "</pre>";
  }
}
